package com.xq.tmall.agu.core.agent.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    public static SqlSession getSqlSession() {
        SqlSession sqlSession;
        try {
            //创建配置信息输入流
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            //创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //创建SqlSessionFactory对象
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
            //实例化SqlSession对象
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sqlSession;
    }

    public static void closeSqlSessionAndCommit(SqlSession sqlSession) {
        sqlSession.commit();
        sqlSession.close();
    }

}
